<?php
// Saves a HTTP URL for a single agent, making it persistent
// POST parameters:
//  permURL: a permanent URL from llHTTPServer 
//  signature: to make spoofing harder
//  timestamp: in-world timestamp retrieved with llGetTimestamp()
//  request: currently only delete (to remove entry from database when the bot dies)

if (isset($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY']))
{
	require_once($_SERVER['DOCUMENT_ROOT'] . "/config.php");
	include(ABS_PATH . "misc/functions.php");
	
	// check for valid signature
	// try to calculate the signature
	if (isset($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY']))
	{
			// this is coming from SL, so we have the object key
		$signature = md5($_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY'] . $_REQUEST['timestamp'] . ':9876') ;
	
		if ($signature != $_REQUEST['signature'])
		{
			header("HTTP/1.0 503 Service Unavailable");
			die("Signature does not match - hack attempt?");		
		}
							
// store entry on SQLite3 database
		try {
			$db = new PDO(PDO_PREFIX . SQLITE_DB_FILENAME);
		}
	
		catch(PDOException $e)
		{
			header("HTTP/1.0 503 Service Unavailable");
  			printf("Connect failed: %s\n", $e->getMessage());
   			_log(__FILE__ . " - line " . __LINE__ . ": Error connecting to database from SL: " . $e->getMessage());
    		exit();
    	}

		if (isset($_REQUEST['permURL'])) // bot registration
		{
			$query = "REPLACE INTO Agents (`UUID`, `Name`, `OwnerKey`, `OwnerName`, `PermURL`, `Location`, `Position`, `Rotation`, `Velocity`, `Energy`, `Money`, `Happiness`, `Class`, `SubType`, `LastUpdate`) VALUES ('" .
				$_SERVER['HTTP_X_SECONDLIFE_OBJECT_KEY'] . "','" .
				addslashes($_SERVER['HTTP_X_SECONDLIFE_OBJECT_NAME']) . "','" .
				$_SERVER['HTTP_X_SECONDLIFE_OWNER_KEY'] . "','" .
				addslashes($_SERVER['HTTP_X_SECONDLIFE_OWNER_NAME']) . "','" .
				$_REQUEST['permURL'] . "','" .
				$_SERVER['HTTP_X_SECONDLIFE_REGION'] . "','" .
				trim($_SERVER['HTTP_X_SECONDLIFE_LOCAL_POSITION'], " ()<>") . "','" .
				trim($_SERVER['HTTP_X_SECONDLIFE_LOCAL_ROTATION'], " ()<>") . "','" .
				trim($_SERVER['HTTP_X_SECONDLIFE_LOCAL_VELOCITY'], " ()<>") . "','" .
				$_REQUEST['energy'] . "','" .	// probably this won't come from in-world but set by the engine
				$_REQUEST['money'] . "','" .
				$_REQUEST['happiness'] . "','" .
				$_REQUEST['class'] . "','" .
				$_REQUEST['subtype'] . "','" .
				$_REQUEST['timestamp'] . "')";
			
			try {
				$db->exec($query);
			}
			
			catch(PDOException $e) {
				header("HTTP/1.0 503 Service Unavailable");
	   			printf("REPLACE query '%s' failed: '%s'\n", $query, $e->getMessage());
	   			_log(__FILE__ . " - line " . __LINE__ . ": REPLACE query '" . $query . "' failed: " . $e->getMessage());
	    		exit();
			}
			_log(__FILE__ . " - line " . __LINE__ . ": REPLACE query '" . $query . "' succeeded! Agent created or updated.");
			header("HTTP/1.0 200 OK");
			header("Content-type: text/plain; charset=utf-8");
			echo "'" . $_SERVER['HTTP_X_SECONDLIFE_OBJECT_NAME'] . "' successfully updated object for NPC '"
				. addslashes($_SERVER['HTTP_X_SECONDLIFE_OWNER_NAME']) . "' ("
				. $_SERVER['HTTP_X_SECONDLIFE_OWNER_KEY'] . "), energy="
				. $_REQUEST['energy'] . ", money=" .
				$_REQUEST['money'] . ", happiness=" .
				$_REQUEST['happiness'] . ", class=" .
				$_REQUEST['class'] . ", subtype=" .
				$_REQUEST['subtype'] . ".";
		}
		else if (isset($_REQUEST['request']) && $_REQUEST['request'] == 'delete') // other requests, currently only deletion
		{
			$query = "DELETE FROM Agents WHERE UUID='" . $_REQUEST['npc'] . "'";
			
			try {
				$db->exec($query);
			}
			
			catch(PDOException $e) {
				header("HTTP/1.0 503 Service Unavailable");
	   			printf("DELETE query '%s' failed: '%s'\n", $query, $e->getMessage());
	   			_log(__FILE__ . " - line " . __LINE__ . ": DELETE query '" . $query . "' failed: " . $e->getMessage());
	    		exit();
			}
			header("HTTP/1.0 200 OK");
			header("Content-type: text/plain; charset=utf-8");
			echo "'" . $_REQUEST['npc'] . "' successfully deleted.";
			_log(__FILE__ . " - line " . __LINE__ . ": DELETE query '" . $query . "' succeeded");
			
			
		}
		else
		{
			header("HTTP/1.0 405 Method Not Allowed");
			echo "Unknown request: " . print_r($_REQUEST, TRUE);
			_log(__FILE__ . " - line " . __LINE__ . ": unknown request - " . print_r($_REQUEST, TRUE)); 
		}
	}
	else
	{
		header("HTTP/1.0 503 Service Unavailable");
		echo "Signature not found";
	}
}
else
{
	header("HTTP/1.0 405 Method Not Allowed");
	echo "Only in-world requests allowed";
}
?>
